package cn.wizzer.app.web.modules.controllers.user;


import cn.wizzer.app.user.modules.models.UserAddress;
import cn.wizzer.app.user.modules.services.UserAddressService;
import cn.wizzer.app.web.commons.filter.ApiTokenFilter;
import cn.wizzer.framework.filter.ParamFilter;
import cn.wizzer.framework.util.Result;
import cn.wizzer.framework.util.param.ParamVerify;
import com.alibaba.dubbo.config.annotation.Reference;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.Mvcs;
import org.nutz.mvc.annotation.*;

@IocBean
@At("/api/user/address")
public class ApiUserAddressController {
    @Inject
    @Reference
    private UserAddressService addressService;


    /**
     * 收货地址列表(分页)
     *
     * @param pageNumber int
     * @param pageSize   int
     * @return Object
     */
    @At("/list")
    @Ok("json")
    @Filters(@By(type = ApiTokenFilter.class))
    public Object list(@ParamVerify(required = true, name = "pageNumber") int pageNumber,
                       @ParamVerify(required = true, name = "pageSize") int pageSize) {
        String userId = Mvcs.getReq().getHeader("appid");
        return Result.success().addData(addressService.listPage(pageNumber, pageSize, userId));
    }


    /**
     * 添加收货地址
     *
     * @param userAddress UserAddress
     * @return Object
     */
    @At("/add")
    @Ok("json")
    @Filters(@By(type = ApiTokenFilter.class))
    public Object add(@Param("..") UserAddress userAddress) {
        String appid = Mvcs.getReq().getHeader("appid");
        Result result = addressService.validate(userAddress);
        if (result.getCode() == 0) {
            userAddress.setUserId(appid);
            addressService.insert(userAddress);
        }
        return result;
    }


    /**
     * 删除收货地址
     *
     * @param id String 地址id
     * @return Object
     */
    @At("/delete")
    @Ok("json")
    @Filters(@By(type = ApiTokenFilter.class))
    public Object delete(@ParamVerify(name = "id", required = true) String id) {
        // 伪删除
        addressService.vDelete(id);
        return Result.success();
    }


    /**
     * 设置默认收货地址
     *
     * @param id String 地址id
     * @return Object
     */
    @At("/setDefault")
    @Ok("json")
    @Filters(@By(type = ApiTokenFilter.class))
    public Object setDefault(@ParamVerify(name = "id", required = true) String id) {
        String appid = Mvcs.getReq().getHeader("appid");
        addressService.update(Chain.makeSpecial("addressDefault", "(id = '" + id + "')"), Cnd.where("userId", "=", appid));
        return Result.success();
    }

    // 暂无修改功能,只有删除
}
